package click

class Task {
    String name
    Boolean available = false
    Integer seek =0

    
    Website website;

    static hasMany = [actions: WebAction]
    static belongsTo = WebAction

    static constraints = {
        name(size:1..50,blank:false ) 
        website();
        actions(nullable: true)
        seek()
    }

    static mapping = {
        actions sort  : "sortid"
       
    }
    String toString(){
        "${name}"
    }
    String buildAction(){
        def result =''
        if (actions) {
            actions.each{
                result += "${it.name} , ${it.target}${it.value?' , '+it.value:''}\r\n"
            }
        } 
        return result
    }

    String buildToJSON(){
        def result =''
        if (actions) {
            actions.each{
                result += "${it.name} , ${it.target}${it.value?' , '+it.value:''}||"
            }
        } 
        return result
    }

    static String selectTasks(Website website){
                   // 通过时间验证的才可以执行
                def result
                def tasks = Task.findAllByWebsiteAndAvailable(website,true);
                if (tasks && !tasks.isEmpty()) {
                     
                    def seek = Math.random() * tasks?.seek.sum()
                    def tasks_count=0;
                    def f = true;
                    tasks.each{ v  ->
                        tasks_count += v.seek;
                        if (tasks_count > seek && f) { //可用的任务 
                            def content = v.buildToJSON()
                            if (content != '') {
                                println  content
                                result =   "\"${content}\"" 
                                f = false;
                                website.total = website.total + 1 
                            }
                        }
                    } 
                }
                 return  result
    }
}

